package myzzyl.service.Impl;


import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.ListProductsRequest;
import com.huaweicloud.sdk.iotda.v5.model.ListProductsResponse;
import myzzyl.constants.CommonStrField;
import myzzyl.constants.ErrorConstants;
import myzzyl.constants.ResponseCode;
import myzzyl.domain.vo.ProductVo;
import myzzyl.exception.BusinessException;
import myzzyl.service.IotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Iot相关请求接口
 */
@Service
public class IotServiceImpl implements IotService {

    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 同步华为云Iot管理平台下的所有产品，并缓存到redis中
     */
    @Override
    public void syncProductList() {
        // 调用listProducts获取Iot平台下的产品
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);

        // 判断响应码是否为200
        if (response.getHttpStatusCode() != ResponseCode.SUCCESS.getCode()) {
            throw new BusinessException(ErrorConstants.LIST_PRODUCTS_ERROR);
        }


        // 存入redis中
        redisTemplate.opsForValue().set(CommonStrField.IOT_PRODUCT.getStr(),
                JSONUtil.toJsonStr(response.getProducts()));
    }


    /**
     * 获取华为云Iot管理平台下的所有产品
     * @return 返回值
     */
    @Override
    public List<ProductVo> allProduct() {
        // 从redis中查询
        String productStr = redisTemplate.opsForValue()
                .get(CommonStrField.IOT_PRODUCT.getStr());

        return JSONUtil.toList(productStr, ProductVo.class);
    }


}
